"""
日志查看工具
用于查看和分析日志文件
"""
import os
import sys
import argparse
from datetime import datetime

def view_log(log_file, lines=100, search=None, errors_only=False):
    """查看日志文件内容"""
    try:
        # 确保文件存在
        if not os.path.exists(log_file):
            print(f"错误: 日志文件 '{log_file}' 不存在")
            return False
        
        # 读取文件
        with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
            all_lines = f.readlines()
        
        # 过滤行数
        if lines > 0:
            log_lines = all_lines[-lines:]
        else:
            log_lines = all_lines
        
        # 过滤错误信息
        if errors_only:
            log_lines = [line for line in log_lines if 'ERROR' in line.upper() or 'EXCEPTION' in line.upper()]
        
        # 查找关键词
        if search:
            log_lines = [line for line in log_lines if search.lower() in line.lower()]
        
        # 打印结果
        if log_lines:
            print(f"\n==== 日志文件: {log_file} ====")
            if lines > 0 and len(all_lines) > lines:
                print(f"显示最后 {len(log_lines)} 行(共 {len(all_lines)} 行)")
            else:
                print(f"显示所有 {len(log_lines)} 行")
                
            print("=" * 80)
            for line in log_lines:
                print(line.rstrip())
            print("=" * 80)
            return True
        else:
            print(f"没有找到匹配的日志条目")
            return False
    
    except Exception as e:
        print(f"查看日志时出错: {str(e)}")
        return False

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="日志查看工具")
    parser.add_argument('log_file', nargs='?', default='backend.log', help='日志文件路径')
    parser.add_argument('-l', '--lines', type=int, default=100, help='显示的行数')
    parser.add_argument('-s', '--search', type=str, help='搜索关键词')
    parser.add_argument('-e', '--errors', action='store_true', help='只显示错误')
    
    args = parser.parse_args()
    
    view_log(args.log_file, args.lines, args.search, args.errors)

if __name__ == "__main__":
    main() 